package com.example.demo.controller;

import com.example.demo.pojo.Book;
import com.example.demo.pojo.Borrow;
import com.example.demo.pojo.User;
import com.example.demo.pojo.UserInfo;
import com.example.demo.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class UserController {
    @Autowired
    private UserServiceImpl service;
    @RequestMapping("/findUser")
    @ResponseBody
    public  List<User> findUser(){
        User user =new User();
        return service.findUser(user);
    }

    @PostMapping("/insertUserInfo")
    @ResponseBody
    public void insertUserInfo(@RequestBody UserInfo userInfo) {
//        System.out.println(user);
        service.insertUserInfo(userInfo);
    }

    @PostMapping("/insertUser")
    @ResponseBody
    public void createUser(@RequestBody User user) {
//        System.out.println(user);
        service.insertUser(user);
    }

    @RequestMapping("/getBooks")
    @ResponseBody
    public  List<Book> getBooks( ) {
        Book book = new Book();
//        System.out.println( service.getBooks(book));
        return service.getBooks(book);
    }

    @PostMapping("/insertBook")
    @ResponseBody
    public void insertBook(@RequestBody Book book) {
        System.out.println(book);
        service.insertBook(book);
    }

    @PostMapping("/getBorrow")
    @ResponseBody
    public List<Map<String, Object>> getBorrow(@RequestBody User user ) {
        System.out.println(user.getUserName());
        System.out.println( service.getBorrow(user.getUserName()));
        return service.getBorrow(user.getUserName());
    }
    @PostMapping("/BorrowBook")
    @ResponseBody
    public void insertBook(@RequestBody Borrow borrow) {
//        System.out.println(borrow);
        service.BorrowBook(borrow);
    }


    @PostMapping("/returnBook")
    @ResponseBody
    public void returnBook(@RequestBody Borrow borrow) {
        System.out.println(borrow);
        service.returnBook(borrow);
    }

    @PostMapping("/updateStatus")
    @ResponseBody
    public void updateStatus(@RequestBody Borrow borrow) {
        System.out.println(borrow);
        service.updateStatus(borrow);
    }



    @PostMapping("/userInfo")
    @ResponseBody
    public  List<UserInfo> getUserInfo(@RequestBody int id ) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(id);
//        System.out.println(id);
        return service.getUserInfo(userInfo);
    }


    @PostMapping("/updateUserInfo")
    @ResponseBody
    public  void  updateUserInfo(@RequestBody UserInfo userInfo ) {
//        System.out.println(userInfo.getBirthday());
        service.updateUserInfo(userInfo);
    }
    @PostMapping("/updateBook")
    @ResponseBody
    public  void  updateBook(@RequestBody Book book ) {
//        System.out.println(userInfo.getBirthday());
        service.updateBook(book);
    }



    @PostMapping("/updateUser")
    @ResponseBody
    public  void  updateUser(@RequestBody User user ) {
        System.out.println(user);
        service.updateUser(user);
    }

    @PostMapping("/deleteUser")
    @ResponseBody
    public  void  deleteUser(@RequestBody User user ) {
//        System.out.println(user);
        service.deleteUser(user);
    }
    @PostMapping("/deleteUserByIds")
    @ResponseBody
    public  void  deleteUserByIds(@RequestBody List<Integer> ids ) {
//        System.out.println(ids);
        service.deleteUserByIds(ids);
    }




























    @RestController
    @RequestMapping("/uploadImage")
    public class ImageUploadController {

        private final String IMAGE_DIR = Paths.get(
                System.getProperty("user.dir"),
                "src/main/resources/static/images"
        ).toString();

        @PostMapping
        public Map<String, Object> uploadImage(
                @RequestParam("file") MultipartFile file) {

            Map<String, Object> response = new HashMap<>();

            try {
                // 1. 验证图片
                if (!file.getContentType().startsWith("image/")) {
                    throw new IllegalArgumentException("只允许上传图片文件");
                }

                // 2. 创建目录（如果不存在）
                Path dirPath = Paths.get(IMAGE_DIR);
                if (!dirPath.toFile().exists()) {
                    dirPath.toFile().mkdirs();
                }

                // 3. 生成唯一文件名
                String originalName = file.getOriginalFilename();
                String extension = originalName.substring(originalName.lastIndexOf("."));
                String newFilename = UUID.randomUUID() + extension;

                // 4. 保存文件
                Path filePath = dirPath.resolve(newFilename);
                file.transferTo(filePath.toFile());

                UserInfo userInfo = new UserInfo();
                userInfo.setUserId(1);
                userInfo.setAvatar(newFilename);
                service.updateUserInfo(userInfo);

                // 5. 返回访问URL
                response.put("success", true);
                response.put("url", "/uploadImage/" + newFilename);

            } catch (IOException e) {
                response.put("success", false);
                response.put("error", "文件保存失败");
            } catch (Exception e) {
                response.put("success", false);
                response.put("error", e.getMessage());
            }

            return response;
        }

        @Configuration
        public class WebConfig implements WebMvcConfigurer {

            @Value("${file.storage.location}") // 确保application.yml中有此配置
            private String uploadDir;

            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/uploadImage/**")
                        .addResourceLocations("file:" + uploadDir + "/")
                        .setCachePeriod(3600);

                // 开发环境额外映射（可选）
                if (isDevMode()) {
                    Path devPath = Paths.get("src/main/resources/static/uploadImage");
                    registry.addResourceHandler("/dev-images/**")
                            .addResourceLocations("file:" + devPath.toAbsolutePath() + "/");
                }
            }

            private boolean isDevMode() {
                return ManagementFactory.getRuntimeMXBean()
                        .getInputArguments().toString().contains("idea");
            }
        }
    }
}
